import {
  mapActions
} from 'vuex'

import uploadImg from './components/upload-img.vue'
import kpsImageCutter from '@/components/ksp-image-cutter/ksp-image-cutter.vue'

export default {
  components: {
    uploadImg,
    kpsImageCutter
  },

  data() {
    return {
      roleId: 0, //权限
      navBack: true, //是否开启返回
      addNumber: 0,
      currentIndex: 0, //当前
      img: [],
      show: false,
      list: null, //企业信息
      Reason: '', //企业描述
      Address: '', //公司注册地址
      userInfo: '', //超管信息
      logoUrl: '', //logo地址
      StoreName: '', //店铺名
      storeId: '', //店铺id
      roleName: '', //角色名，权限
      menberList: [], //成员列表
      companyIdqwe: '',
      role: 0,
      doorPhoto: [],
      environmentalPhoto: [],
      qualificationsPhoto: [],
      countNum: 0, //描述字数
      saveBtn: false, //是否保存
      saveField: {
        reason: '',
        doorPhoto: '',
        environmentalPhoto: '',
        qualificationsPhoto: '',
      },
      // 检测是否修改
      saveshow: false, //提示是否保存
      goNextStatus: false, //表示是跳转下个页面还是返回上个页面
      goNextNum: 0,
      // 图片裁剪
      url: '',
      path: '',
      selectLog: true, //选择图片为true
      discshow: false, //描述text是否可编辑
      type: 100, //默认返回类型
      canBank: true
    }
  },
  // 监听返回
  onBackPress(e) {
    if (this.canBank) {
      this.goNextStatus = false
      this.saveChange()
      return this.saveshow
    } else {
      console.log(12231)
      return true

    }

  },
  onShow() {
    this.getReceiverAddressCount()
    this.getCompanyInfo() //获取公司id
    this.user()
    this.saveshow = false //提示是否保存
    this.discshow = false
    this.goNextStatus = false //表示是跳转下个页面还是返回上个页面
    this.goNextNum = 0
    this.saveBtn = false
    this.role = this.$store.state.user.userInfo.role
  },
  filters: {
    formatStoreType(data) {
      let text = ''
      switch (Number(data)) {
      case 0:
        text = '美宝护精品供应商'
      case 1:
        text = '7迈直营养护'
        break
      case 2:
        text = '车源商'
      case 3:
        text = '汽贸店'
        break
      case 4:
        text = '4s店'
      case 5:
        text = '7迈直营店'
        break
      case 6:
        text = '7迈直营美宝护'
        break
      case 7:
        text = '主机厂'
        break
      case 8:
        text = '养护门店'
        break
      case 9:
        text = '自助洗车加盟商'
        break
      case 10:
        text = '自助洗车区域合作商'
        break
      case 11:
				  text = '自助洗车物业管理'
				  break

      default:
        text = ''
        break
      }
      return text
    },
    cutString(str, len) {
      if (str.length * 2 <= len) {
        return str
      }
      let strlen = 0
      let s = ''
      for (let i = 0; i < str.length; i++) {
        s = s + str.charAt(i)
        if (str.charCodeAt(i) > 128) {
          strlen = strlen + 2
          if (strlen >= len) {
            return s.substring(0, s.length - 1) + '...'
          }
        } else {
          strlen = strlen + 1
          if (strlen >= len) {
            return s.substring(0, s.length - 2) + '...'
          }
        }
      }
      return s
    },
  },
  created() {
    this.getStoreImgDetail()
  },

  methods: {
    //用户信息
    async user() {
      try {
        let data = {
          Uid: uni.getStorageSync('Ztc_B_USER_INFO').tid,
        }
        const res = await this.$api.company.getCompanyUserInfo(data)
        this.roleId = res.data.role
        this.$store.commit('setUserRole', res.data.role)
        this.$store.commit('user/setUserRole', res.data.role)
        let userInfo = uni.getStorageSync('Ztc_B_USER_INFO')
        let userInfoDetail = uni.getStorageSync('userInfoDetail')
        userInfo.role = res.data.role
        userInfoDetail.user.roleName = res.data.roleName
        uni.setStorageSync('Ztc_B_USER_INFO', userInfo)
        uni.setStorageSync('userInfoDetail', userInfoDetail)

      } catch (e) {
        console.log(e)
      }
    },
    //店铺照片
    async getStoreImgDetail() {
      const res = await this.$api.company.getStoreImgDetail()
      // console.log(res)
      this.doorPhoto = res.data.topImg
      this.environmentalPhoto = res.data.environmentalImg
      this.qualificationsPhoto = res.data.certificatesImg

      this.saveField.doorPhoto = res.data.topImg
      this.saveField.environmentalPhoto = res.data.environmentalImg
      this.saveField.qualificationsPhoto = res.data.certificatesImg
      // console.log(res)
    },
    //成员列表
    async updateStoreImg() {

      try {
        let data = {
          'topImg': this.doorPhoto,
          'environmentalImg': this.environmentalPhoto,
          'certificatesImg': this.qualificationsPhoto
        }
        const res = await this.$api.company.updateStoreImg(data)
        // console.log(res,'成员列表')
        this.menberList = res.data.list
        // this.$forceUpdate()
      } catch (e) {
        console.log(e)
      }
    },
    async getReceiverAddressCount() {

      try {
        let data = {
          'app_type': 0
        }
        const res = await this.$api.company.getReceiverAddressCount(data)
        this.addNumber = res.data
      } catch (e) {
        console.log(e)
      }
    },
    goYg() {
      this.$u.toast('员工不能邀请')
    },
    open() {
      this.show = true
    },
    //我的企业信息
    async getCompanyInfo() {
      try {
        let data = {
          StoreId: this.$store.state.userInfoDetail.store
            .storeId, //'de39ade6cc0944ac99e1a02cc8f7c729'
        }
        const res = await this.$api.company.getCompanyInfo(data)
        // console.log(res, '企业信息')
        this.Reason = res.data.reason
        this.countNum = this.Reason.length
        this.Address = res.data.address
        this.StoreName = res.data.storeName
        this.list = res.data
        this.companyIdqwe = res.data.companyId //本页面获取公司id存储
        this.logoUrl = res.data.logo
        let companyIds = res.data.companyId //存公共方法六里面
        this.$store.dispatch('getCompanyId', companyIds)

        this.saveField.reason = this.Reason

        this.getCompanyMemberList() // 成员列表
      } catch (e) {
        console.log(e)
      }
    },
    // 成员列表
    async getCompanyMemberList() {
      try {
        let data = {
          PageIndex: 1,
          PageSize: 4,
          CompanyId: this.companyIdqwe, //'f1b343b44a6648c68349d406b62e0c7a'
        }
        const res = await this.$api.company.getCompanyMemberList(data)
        // console.log(res,'成员列表')
        this.menberList = res.data.list
        // this.$forceUpdate()
      } catch (e) {
        console.log(e)
      }
    },
    //上传logo
    uploadAvatar() {
      // const that = this

      uni.chooseImage({
        sizeType: ['compressed'],
        count: 1,
        success: res => {
          console.log(res)
          this.url = res.tempFilePaths[0]
          // let imgdata = this.compress(res.tempFilePaths[0],0.6)
          // console.log(imgdata)
          // this.$base64Img( this.url ).then(ress => {		//调用全局方法
          //               console.log(ress)					//控制台打印出图片base64值
          //               // this.imgs.push(res)     			//添加到图片数组上进行渲染
          //           })

          this.selectLog = false
        },
        fail: err => {
          this.selectLog = true
        }

      })
      // this.selectLog =this.url?false:true

    },
    storeBlur(e) {
      // console.log(e)
      this.StoreName = e
      this.updateCompanyInfo(1)
    },
    // 压缩图片
		      // compress(img, size) {
		      //   let canvas = document.createElement('canvas')
		      //   let ctx = canvas.getContext('2d')
		      //   let initSize = img.src.length
		      //   let width = img.width
		      //   let height = img.height
		      //   canvas.width = width
		      //   canvas.height = height
		      //   // 铺底色
		      //   ctx.fillStyle = '#fff'
		      //   ctx.fillRect(0, 0, canvas.width, canvas.height)
		      //   ctx.drawImage(img, 0, 0, width, height)
		      //   //进行最小压缩
		      //   let ndata = canvas.toDataURL('image/jpeg', size)
		      //   console.log('*******压缩后的图片大小*******')
		      //   // console.log(ndata)
		      //   console.log(ndata.length / 1024)
		      //   return ndata
		      // },

    descInput() {
      if (this.Reason.length > 150) {
        this.Reason = this.Reason.slice(0, 150)
      }
      this.countNum = this.Reason.length
    },
    //保存资料
    async updateCompanyInfo(type) {
      // type:1---表示需要静默保存的 2----点击按钮保存
      if (type === 1) {
        uni.showLoading({
          title: '上传中'
        })
      } else {
        this.canBank = false
      }
      try {
        let data = {
          CompanyId: this.list.companyId,
          Logo: this.logoUrl,
          StoreName: this.StoreName || this.list.companyName,
          Reason: this.Reason,
        }
        const res = await this.$api.company.updateCompanyInfo(data)
        if (this.doorPhoto.length !== 0 || this.environmentalPhoto.length !== 0 || this.qualificationsPhoto
          .length !== 0) {
          if (this.doorPhoto.length === 0) {
            this.$u.toast('门头照不能为空')
            return false
          }

        }
        console.log(res, type)
        if (type === 2) {
          this.updateStoreImg()
          this.getStoreList()
          this.saveshow = false
          this.discshow = false
          this.saveBtn = true
          this.$refs.uToast.show({
            title: '保存成功',
            type: 'success',
          })
          if (this.goNextStatus) {
            setTimeout(() => {
              this.goPage(this.goNextNum)
            }, 1500)
          } else {
            this.$refs.uToast.show({
              title: '保存成功',
              type: 'success',
              back: true
            })
          }
          this.canBank = true
        } else {

          let userInfo = uni.getStorageSync('userInfoDetail')
          userInfo.store.storeName = this.StoreName
          uni.setStorageSync('userInfoDetail', userInfo)
          this.canBank = true
          // console.log(uni.getStorageSync('userInfoDetail'))
          uni.hideLoading()
        }
        // console.log(this.doorPhoto,'123123')
      } catch (e) {
        if (type === 1) {
          uni.hideLoading()
        }
        console.log(e)
      }
    },
    saveChange() {
      // console.log(1122222)
      if (this.saveField.reason !== this.Reason || this.saveField.doorPhoto !== this.doorPhoto || this.saveField
        .environmentalPhoto !==
				this.environmentalPhoto || this.saveField.qualificationsPhoto !== this.qualificationsPhoto) {
        if (!this.saveBtn) {
          this.saveshow = true
          this.discshow = true
        }
      }
      // console.log(3333, this.saveshow, this.saveField.reason, this.Reason)

    },
    // 获取店铺列表
    async getStoreList() {
      try {
        const res = await this.$api.store.GetStoreList({
          PageIndex: 1,
          PageSize: 100,
        })
        console.log('店铺列表', res)
        let storeId = this.$store.state.userInfoDetail.store.storeId
        // 店铺列表
        this.storeList = res.data.list.filter(
          item => item.storeId !== storeId
        )
        // 当前店铺
        let storeInfo = res.data.list.find(
          item => item.storeId === storeId
        )
        let userInfo = uni.getStorageSync('userInfoDetail')
        userInfo.store = storeInfo
        uni.setStorageSync('userInfoDetail', userInfo)

        console.log(storeInfo)
      } catch (err) {
        console.log(err)
      }
    },

    goMenber() {
      // console.log(this.list.applyCount)
      if (Number(this.list.applyCount) === 0) {
        this.$u.toast('当前无成员审核申请')
        return false
      } else {
        uni.navigateTo({
          url: '../menber/menber',
        })
      }
      // let e = this.list.companyId
      // console.log(this.list.companyId)

    },
    //页面跳转
    goInfo(item) {
      // this.goNextNum = 1
      // console.log(item)
      let id = JSON.stringify(item)
      uni.navigateTo({
        url: '/pages_common/pages_me/personalInfo/personalInfo?uid=' + id,
      })
    },
    // 取消保存
    closeAll() {
      this.Reason = this.saveField.reason
      this.topImg = this.saveField.doorPhoto
      this.environmentalImg = this.saveField.environmentalPhoto
      this.certificatesImg = this.saveField.qualificationsPhoto
      this.saveshow = false
      this.discshow = false
      if (this.goNextNum === 0) {
        uni.navigateBack()
      } else {
        this.goPage(this.goNextNum)
      }
    },
    onok(ev) {
      this.path = ev.path
      // this.logoUrl=ev.path
      // this.url=ev.path
      console.log(ev.path)
      this.$api.files
        .uploadImg({
          filePath: this.path,
        })
        .then(res => {
          console.log(res)
          this.logoUrl = res.baseUrl + res.url

          this.url = ''
          this.updateCompanyInfo(1)
        })
        .catch(err => {
          console.log(err)
        })
      this.selectLog = true
    },
    oncancle() {
      // url设置为空，隐藏控件
      this.url = ''
      this.selectLog = true
    },
    //页面跳转
    goPage(type) {
      this.goNextNum = type
      let that = this
      new Promise(function(resolve, reject) {
        that.saveChange()
        resolve(that.saveshow)
      }).then((res, rej) => {
        if (res) {
          this.saveshow = true
          this.discshow = true
          this.goNextStatus = true

        } else {
          if (type === 2) {
            // 收货地址
            uni.navigateTo({
              url: '/pages_common/meShipAddress/meShipAddress',
            })
          } else if (type === 1) {
            // 成员
            uni.navigateTo({
              url: '../menber/menber',
            })
          } else if (type === 3) {
            // 邀请成员
            uni.navigateTo({
              url: '../invite/invite',
            })
          }

        }
      })

    },
    // //邀请
    // goAdd(bagName, url) {
    //   let that = this
    //   new Promise(function(resolve, reject) {
    //     that.saveChange()
    //     resolve(that.saveshow)
    //   }).then((res, rej) => {
    //     if (res) {
    //       this.saveshow = true
    //       this.goNextStatus = true
    //       this.goNextNum = 3
    //     } else {
    //       uni.navigateTo({
    //         url: '../invite/invite',
    //       })
    //     }
    //   })
    // },
  },
}
